package org.foreveross.que.applicationImpl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.foreveross.que.infra.base.constant.SysConstants;
import org.openkoala.koala.auth.core.domain.Role;
import org.openkoala.koala.auth.core.domain.RoleUserAuthorization;
import org.openkoala.koala.auth.core.domain.User;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.utils.DateUtils;
import org.foreveross.que.application.FbUserApplication;
/**
 * 问题反馈用户业务类
 * @author lyq
 *
 */
@Service
public class FbUserApplicationImpl implements FbUserApplication {
	protected static Logger logger = Logger.getLogger(FbUserApplicationImpl.class);
	@Transactional
	public void saveUser(String username,String sysType){
		Date currDate = new Date();
		RoleUserAuthorization r = null;
//		baseRepository.get(User.class, acUser.getIds()+"");
		User oldUser = User.findByUserAccount(username);
		User user = new User();
		if(oldUser!=null){
			user = oldUser;
			user.setLastLoginTime(currDate);
			logger.info("login new user "+username);
		}else{
			user.setCreateDate(currDate);
			r = new RoleUserAuthorization();
			r.setAbolishDate(DateUtils.MAX_DATE);
			r.setCreateDate(currDate);
			Role role = new Role();
			role.setId(3L);
			r.setRole(role);
			r.setUser(user);
			r.setVersion(0);
			
			user.setLastLoginTime(currDate);
			user.setAbolishDate(DateUtils.MAX_DATE);
			user.setLastModifyTime(currDate);
			user.setName(username);
			user.setSerialNumber("0");
			user.setSortOrder(0);
			user.setUserAccount(username);
			MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("MD5");
			user.setCreateOwner(sysType);
			user.setValid(true);
			user.setVersion(0);
			String pass = encoder.encodePassword(SysConstants.DEFAULT_PASS, username);
			user.setUserPassword(pass);
			logger.info("insert new user "+username);
		}
		user.save();
		if(r!=null){
			r.save();
		}
	}
}
